package com.demo.config;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * @author : YU.TAN
 * @date : 2021/9/27 11:00
 * RedisConfig配置类，相当于配置了RedisTemplate、和StringRedisTemplate
 */
@Configuration
@RequiredArgsConstructor
public class RedisConfig {

//    @Autowired
    /**
     *
     */
    private final RedisConnectionFactory redisConnectionFactory;


    @Bean("functionDomainRedisTemplate")
    public RedisTemplate<String, Object> functionDomainRedisTemplate() {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        initDomainRedisTemplate(redisTemplate, redisConnectionFactory);
        return redisTemplate;
    }

    /**
     * 设置redisTemplate序列化策略，否则在使用redisTemplate的时候在redis的客户端查看会出现乱码
     *
     * @param redisTemplate
     * @param factory
     */
    private void initDomainRedisTemplate(RedisTemplate<String, Object> redisTemplate,
                                         RedisConnectionFactory factory) {
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        // 使用 GenericFastJsonRedisSerializer 替换默认序列化
//        GenericFastJsonRedisSerializer genericFastJsonRedisSerializer = new GenericFastJsonRedisSerializer();
        RedisSerializer stringSerializer = new StringRedisSerializer();

        // 设置key和value的序列化规则
//        redisTemplate.setKeySerializer(new GenericToStringSerializer<>(Object.class));
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        // 设置hashKey和hashValue的序列化规则
//        redisTemplate.setHashKeySerializer(new GenericToStringSerializer<>(Object.class));
        redisTemplate.setHashKeySerializer(stringSerializer);
        redisTemplate.setHashValueSerializer(stringSerializer);
        // 设置支持事物
        redisTemplate.setEnableTransactionSupport(false);
        redisTemplate.afterPropertiesSet();

        redisTemplate.setConnectionFactory(factory);
    }
}
